package com.example.myapplication2;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.*;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.HashMap;

public class ContactsActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_CONTACTS = 1;

    private static final int REQUEST_CODE_SMS = 2;
    private static final String[] PERMISSIONS_CONTACTS = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };

    private static final String[] PERMISSIONS_SMS = new String[]{
            Manifest.permission.READ_SMS,
            Manifest.permission.SEND_SMS
    };
    private TextView name;
    private TextView numberEdit7;
    private TextView mailEdit7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        //检查权限
        checkPermissions(this, PERMISSIONS_CONTACTS, REQUEST_CODE_CONTACTS);

        name = findViewById(R.id.nameEdit7);
        numberEdit7 = findViewById(R.id.numberEdit7);
        mailEdit7 = findViewById(R.id.mailEdit7);
        findViewById(R.id.saveContacts).setOnClickListener(this);
        findViewById(R.id.saveContacts2).setOnClickListener(this);
        findViewById(R.id.updateContacts).setOnClickListener(this);
        findViewById(R.id.deleteContacts).setOnClickListener(this);
        findViewById(R.id.findContactsByName).setOnClickListener(this);
        findViewById(R.id.findContactsAll).setOnClickListener(this);
    }


    //检查多个权限,返回true表示已完全启用权限,返回false表示未完全启用权限
    private boolean checkPermissions(Activity act, String[] permissions, int requestCode) {
        //判定该系统是否拥有动态权限管理,Android6.0之后才有该功能
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int check = PackageManager.PERMISSION_GRANTED;
            for (String permission : permissions) {
                // 检查权限,返回值为-1,即为无相关权限,0即拥有相关权限
                check = ContextCompat.checkSelfPermission(act, permission);
                //判定权限
                if (check != PackageManager.PERMISSION_GRANTED) {
                    //无相关权限,结束检查
                    break;
                }
            }
            if (check != PackageManager.PERMISSION_GRANTED) {
                //检查到未申请该权限,弹窗申请
                ActivityCompat.requestPermissions(act, permissions, requestCode);
                return false;
            }
        }
        Toast.makeText(this, "权限检查完毕,权限正常", Toast.LENGTH_SHORT).show();
        return true;
    }

    private boolean checkGrant(int[] grantResults) {
        if (grantResults != null) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private void jumpToSettings() {
        Intent intent = new Intent();
        //应用的详情设置界面
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //具体某个应用管理页面
        intent.setData(Uri.fromParts("package", getPackageName(), null));
        //跳转应用模式
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //查询用户判定结果
        switch (requestCode) {
            case REQUEST_CODE_CONTACTS:
                if (checkGrant(grantResults)) {
                    Log.d("info", "授权成功");
                } else {
                    Log.d("info", "授权失败");
                    jumpToSettings();
                }
                break;
            case REQUEST_CODE_SMS:
                if (checkGrant(grantResults)) {
                    Log.d("info", "授权成功");
                } else {
                    Log.d("info", "授权失败");
                    jumpToSettings();
                }
                break;
        }
    }

    @Override
    public void onClick(View view) {
        HashMap<String, String> map = new HashMap<>();
        switch (view.getId()) {
            case R.id.saveContacts:
                //保存
                map.put("name", name.getText().toString());
                map.put("number", numberEdit7.getText().toString());
                map.put("mail", mailEdit7.getText().toString());
                addContacts(getContentResolver(), map);
                break;
            case R.id.saveContacts2:
                map.put("name", name.getText().toString());
                map.put("number", numberEdit7.getText().toString());
                map.put("mail", mailEdit7.getText().toString());
                addFullContacts(getContentResolver(), map);
                break;

            case R.id.updateContacts:
                //更新
                break;
            case R.id.deleteContacts:
                //删除
                break;
            case R.id.findContactsByName:
                //根据名字查询
                break;
            case R.id.findContactsAll:
                //查询所有
                ArrayList<HashMap<String, String>> list = readPhoneContacts(getContentResolver());
                if (list.size() > 0) {
                    for (HashMap<String, String> stringStringHashMap : list) {
                        String name = stringStringHashMap.get("name");
                        String phone = stringStringHashMap.get("phone");
                        String mail = stringStringHashMap.get("mail");
                        System.out.println(name + "," + phone + "," + mail);
                    }
                }
                break;
        }
    }

    @SuppressLint("Range")
    private ArrayList<HashMap<String, String>> readPhoneContacts(ContentResolver resolver) {
        ArrayList<HashMap<String, String>> hashMaps = new ArrayList<>();
        Cursor query = resolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID}
                , null, null, null);
        int count = query.getCount();
        if (count > 0) {
            while (query.moveToNext()) {
                int anInt = query.getInt(0);
                Uri parse = Uri.parse("content://com.android.contacts/contacts/" + anInt + "/data");
                Cursor cursorData = resolver.query(parse, new String[]{ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA2, ContactsContract.Data.DATA1}
                        , null, null, null);
                if (cursorData==null){
                    return hashMaps;
                }
                int count1 = cursorData.getCount();
                HashMap<String, String> map = new HashMap<>();
                if ( count1> 0) {
                    while (cursorData.moveToNext()) {
                        String data1 = cursorData.getString(cursorData.getColumnIndex(ContactsContract.Data.DATA1));
                        String data2 = cursorData.getString(cursorData.getColumnIndex(ContactsContract.Data.DATA2));
                        String mimeType = cursorData.getString(cursorData.getColumnIndex(ContactsContract.Data.MIMETYPE));

                        switch (mimeType) {
                            case CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
                                map.put("name", data2);
                                break;
                            case CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
                                map.put("phone", data1);
                                break;
                            case CommonDataKinds.Email.CONTENT_ITEM_TYPE:
                                map.put("mail", data1);
                                break;
                        }
                    }
                    cursorData.close();
                }
                hashMaps.add(map);
            }
            query.close();
        }
        return hashMaps;
    }

    private void addFullContacts(ContentResolver resolver, HashMap<String, String> map) {
        //将所有插入行为进行管控,防止出现插入失败或者出现异常,垃圾数据的自动回滚
        //创建一个主记录
        ContentProviderOperation op_main = ContentProviderOperation
                .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                //防止出现没有实例化ContentValues对象
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .build();
        //姓名操作
        ContentProviderOperation build_name = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                //从0位置的操作的结果取值
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Data.DATA2, map.get("name"))
                .build();
        //电话号码操作
        ContentProviderOperation build_Phone = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Data.DATA1, map.get("number"))
                .withValue(ContactsContract.Data.DATA2, CommonDataKinds.Phone.TYPE_WORK)
                .build();
        //邮箱操作
        ContentProviderOperation build_mail = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Data.DATA1, map.get("mail"))
                .withValue(ContactsContract.Data.DATA2, CommonDataKinds.Email.TYPE_WORK)
                .build();
        //创建集合
        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        operations.add(op_main);
        operations.add(build_name);
        operations.add(build_Phone);
        operations.add(build_mail);
        try {
            resolver.applyBatch(ContactsContract.AUTHORITY, operations);
        } catch (OperationApplicationException e) {
            throw new RuntimeException(e);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    }

    private void addContacts(ContentResolver contentResolver, HashMap<String, String> map) {
        Uri insert = contentResolver.insert(ContactsContract.RawContacts.CONTENT_URI, new ContentValues());
        long rawContactId = ContentUris.parseId(insert);
        //添加姓名
        ContentValues contactsName = new ContentValues();
        contactsName.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        //设置类型
        contactsName.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        contactsName.put(ContactsContract.Data.DATA2, map.get("name"));
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contactsName);
        //添加电话号码
        ContentValues contactsPhone = new ContentValues();
        //ID
        contactsPhone.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        //数据类型
        contactsPhone.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        //设置联系人手机号码
        contactsPhone.put(ContactsContract.Data.DATA1, map.get("number"));
        //设置联系人的手机号码类型,工作.生活
        contactsPhone.put(ContactsContract.Data.DATA2, CommonDataKinds.Phone.TYPE_WORK);
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contactsPhone);


        //添加电子邮箱
        ContentValues contactsMail = new ContentValues();
        //ID
        contactsMail.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        //数据类型
        contactsMail.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        //电子邮箱地址
        contactsMail.put(ContactsContract.Data.DATA1, map.get("mail"));
        //电子邮箱联系类型
        contactsMail.put(ContactsContract.Data.DATA2, CommonDataKinds.Email.TYPE_WORK);
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contactsMail);
    }
}